package com.unytech.project.utils;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import com.unytech.project.common.Globals;

public class VerifyCodeFactory {
//	final private Log logger = LogFactory.getLog(getClass());
	/**
	 * 生成自定义验证码
	 * @param codelen 验证码的位数
	 * @param width 验证码图片的宽度
	 * @param height 验证码图片的高度
	 * @return
	 * @throws Exception
	 */
	public Producer getVerifyCode(Integer codelen, Integer width, Integer height) throws Exception{
    	Producer kaptcha = null;
		Properties proper = new Properties();
		try {
			proper.load(new FileInputStream(new File(this.getClass().getResource("/").getPath()+"kaptcha.properties")));
			
			if (codelen != null && codelen != 0)
				proper.put("kaptcha.textproducer.char.length", codelen);
			if (width != null && width != 0)
				proper.put("kaptcha.image.width", width);
			if (height != null && height != 0)
				proper.put("kaptcha.image.height", height);	
			Config config = new Config(proper);
			kaptcha = config.getProducerImpl();
		} catch (Exception e) {
			if (proper == null || proper.size() == 0) {
				proper.put("kaptcha.session.key", Globals.SESSION_VERIFYCODE_KEY);
				if (codelen != null && codelen != 0)
					proper.put("kaptcha.textproducer.char.length", codelen);
				if (width != null && width != 0)
					proper.put("kaptcha.image.width", width);
				if (height != null && height != 0)
					proper.put("kaptcha.image.height", height);	
			}
			Config config = new Config(proper);
			kaptcha = config.getProducerImpl();
//			logger.info("找不到生成验证码的配置文件，但是仍然以默认配置文件 生成验证码，以下错误是被允许出现的。");
			return kaptcha;
		}
		return kaptcha;
    }
}
